class Admins::MeitisController < Admins::BaseController
  before_action :set_meiti, only: [:show, :edit, :update, :destroy]

  def index
    @meitis = News.includes(:category).where("categories.cataname" => '媒体华理').order("news.created_at desc").page(params[:page])
  end

  def show
  end

  def new
    if params[:meiti].blank?
      @meiti = News.new
    else
      @meiti = News.new(meiti_params)
    end
  end

  def edit
  end

  def create
    meiti_cate = Category.where(:cataname => '媒体华理').first
    @meiti = News.new(meiti_params.merge({postby: current_user.name,:pubtime => Time.now,:category_id => meiti_cate.id,:contribution_units => '媒体华理组'}))
    if @meiti.save
        redirect_to :action => :index, notice: '稿件创建成功'
    else
        flash[:error] = @meiti.errors.full_messages.join(",")
        redirect_to :action => :new,:meiti => @meiti.attributes
    end
  end
  def submit
    @news = News.find(params[:id])
      if @news.update_attributes(check: 1)
        flash[:success] = '稿件送审成功'
        redirect_to :action => :index
      else
         render :edit
      end
  end
  def update
    if @meiti.update(meiti_params)
      flash[:success] = '稿件更新成功'
      redirect_to :action => :index
    else
      flash[:error] = @meiti.errors.full_messages.join(",")
      render :edit
    end
  end

  def change_time
    id = params[:id]
    time =params[:new_time]
    new =News.find_by_id id
    if new
      if new.pubtime
        new.update_attributes(pubtime:Time.parse(time))
      end
    end
    redirect_to '/admins/meitis'
  end
  
  
  def destroy
    @meiti.destroy
    flash[:success] = '稿件删除成功'
    redirect_to :action => :index
  end

  private
    def set_meiti
      @meiti = News.find(params[:id])
    end

    def meiti_params
      params.require(:meiti).permit(:title, :bottomtitle, :uptitle, :author_name, :cameraman_name,
                                    :phone, :contribution_units, :contribution_units_id, :body,
                                    :is_important_news,:keywords,:home_page_image,:writer,:category_id,
                                    :source,:source_url,:writer,:pubtime, :commitime)
    end
end
